using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;

public class SkillDeployer : MonoBehaviour
{
    [HideInInspector] public Rigidbody2D rb;
    [HideInInspector] public Collider2D cd;

    private ISkillSelector selector;
    private BaseImpactEffect[] effects;

    public SkillData skillData;


    #region Skill State Info

    public float skillTimer;
    public Vector3 startPos;

    protected bool canTrigger;
    #endregion

    public List<Transform> targets;

    protected virtual void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        cd = GetComponent<Collider2D>();
    }

    protected virtual void Start()
    {
        
    }

    protected virtual void Update()
    {
        if(skillTimer > 0) skillTimer -= Time.deltaTime;
    }


    public void InitDeployer()
    {
        skillTimer = skillData.durationTime;
        startPos = transform.position;

        selector = DeployerConfigFactory.CreateSkillSelector(skillData);
        effects = DeployerConfigFactory.CreateImpactEffects(skillData);

        for(int i = 0; i < effects.Length; i++) 
        {
            effects[i].skillObject = this.gameObject;
        }
    }

    public void ChooseTarget()
    {
        if (selector != null) targets = selector?.SelectTarget(skillData, this.transform);
    }

    protected virtual void OnTriggerEnter2D(Collider2D collision)
    {
        int layerIndex = 0;

        for(int i = 0; i < 32; i++)
        {
            if (skillData.checkLayer.value == (1 << i)) layerIndex = i;
        }

        canTrigger = layerIndex == collision.gameObject.layer && skillData.triggerType == TriggerType.Trigger;

        if(canTrigger ) 
        {
            for (int i = 0; i < effects.Length; i++)
            {
                effects[i].OnImpactTriggerEntry(collision);
            }

            if (skillData.disappearType.Contains(DisappearType.CheckOver))
                Destroy(this.gameObject);
        }
    }

    #region 可视化

    protected virtual void OnDrawGizmos()
    {
        Gizmos.color = Color.red; 
        Gizmos.DrawWireSphere(transform.position, skillData.attackCheckRange); 
    }

    #endregion


    #region 简写

    public Character owner => skillData.owner.GetComponent<Character>();

    #endregion
}
